package mate.task.odin;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * The initial activity for TaskMate
 * Shows login/registration options
 * @author Chris
 *
 */
public class TaskMateActivity extends Activity {
    /** Called when the activity is first created. */
	
	private EditText password, username;
	private Button login;
	private TextView register;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Removes the top title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.main);	
        
        // The username and password EditText views
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        register = (TextView) findViewById(R.id.register);
        login = (Button) findViewById(R.id.login);

        //Fixes the password hint's font
        password.setTypeface(Typeface.DEFAULT);
        password.setTransformationMethod(new PasswordTransformationMethod());
     
        /*
        //Gives the username EditText a blue stroke
        username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				username.setBackgroundDrawable(getResources().getDrawable(R.drawable.edittext_bg_stroke));
				password.setBackgroundDrawable(getResources().getDrawable(R.drawable.edittext_bg));
			}
		});
        
        */
        //Enter submits
        username.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER){
					if (KeyEvent.ACTION_DOWN == event.getAction()){
						submit();
						return true;
					}
				}
				return false;
			}
		});
        
        /*
        //Gives the password EditText a blue stroke
        password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				password.setBackgroundDrawable(getResources().getDrawable(R.drawable.edittext_bg_stroke));
				username.setBackgroundDrawable(getResources().getDrawable(R.drawable.edittext_bg));
			}
		});
        */
        //Enter submit
        password.setOnKeyListener(new View.OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER){
					if (KeyEvent.ACTION_DOWN == event.getAction()){
						submit();
						return true;
					}
				}
				return false;
			}
		});
        // Goes to Register view when clicked
        register.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent openRegister = new Intent("mate.task.odin.REGISTERACTIVITY");
				startActivity(openRegister);
			}
		});
        
        login.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				submit();
				}				
		});        
    }
    
    public void submit(){
    	UserDatabase db = UserDatabase.getDatabaseInstance();
    	String filename = "user_db.txt";
    	ObjectInputStream inputStream = null; 
        try {
            
            inputStream = new ObjectInputStream(new FileInputStream(filename));
            
            Object obj = null;
            
            while ((obj = inputStream.readObject()) != null) {
                
                if (obj instanceof UserDatabase) {
                	db = (UserDatabase) obj;
                }
                
            }
            
         
        } catch (EOFException ex) { 
            System.out.println("End of file reached.");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the ObjectInputStream
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    
		UserAccount temp = db.login(username.getText().toString(), password.getText().toString());
		if(temp != null){
			Intent openToDo = new Intent("mate.task.odin.TODOLISTACTIVITY");
			startActivity(openToDo);
		}else{
			//print out error (bad login)
			AlertDialog.Builder alert = new AlertDialog.Builder(TaskMateActivity.this);
			alert.setMessage("Your username and password do not match.");
			alert.setTitle("Invalid Login");
			alert.setCancelable(true);
			alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {						
				@Override
				public void onClick(DialogInterface dialog, int which) {							
				}
			});
			alert.show();
		}
    }
    
    public void onPause(){
    	super.onPause();
    }  
    public void onDestroy(){
    	super.onDestroy();
    	finish();
    }
   
}